<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
    <div class="tools" v-loading="loading">
        <div>
            <el-tabs :stretch="true" v-model="toolPanelName">
                <el-tab-pane label="模块" name="modules"></el-tab-pane>
                <!-- <el-tab-pane label="页面" name="pages"></el-tab-pane> -->
                <el-tab-pane label="主题" name="pricolor"></el-tab-pane>
            </el-tabs>

            <div class="pages-list" v-if="toolPanelName == 'pages'">
                <ul class="pages">
                    <li v-for="(pageItem, index) in pages" v-bind:key="index"
                        :class="{ 'page-item': true, active: pageId == pageItem.id }">
                        <div v-if="currentNameEditIndex == index" class="name name-edit">
                            <input @keyup.enter="saveNameHandle" @blur.prevent="saveNameHandle" size="mini"
                                v-model="pageItem.name" placeholder />
                        </div>
                        <div v-else @click="selectPageHandle(pageItem.id)" @dblclick.stop="dbClickHandle(index)"
                            class="name name-display" title="双击改名">
                            <i class="el-icon-s-home" v-if="pageItem.key == 'home'"></i>
                            {{ pageItem.name }}
                        </div>
                        <div class="page-actions">

                            <i :class="{
                                    'el-icon-document-copy': true,
                                }" slot="reference" @click.stop="copyPageHandle(pageItem)" />

                            <el-popover placement="top" width="200" trigger="hover" :disabled="!pageItem.is_system"
                                content="该页面是系统页面，不支持删除">
                                <i :class="{ 'el-icon-delete': true, disabled: pageItem.is_system }" slot="reference"
                                    @click.stop="deletePageHandle(pageItem)" />
                            </el-popover>
                        </div>
                    </li>

                    <li class="page-item add-page" @click.stop="addPageHandle">
                        <i class="el-icon-plus" style="margin-right: 6px" />新建页面
                    </li>

                </ul>
            </div>

            <div class="modules-group" v-else-if="toolPanelName == 'modules'">
                <div class="modules-list" v-for="toolGroup, gindex in tools" v-bind:key=gindex>
                    <div class="tools-title">{{ toolGroup.name }}</div>
                    <div class="tool-item" v-for="(tool, ) in toolGroup.items" v-bind:key="tool.name"
                        @click="toolItemClickHandle(tool)">
                        <img :src="require('@/assets/images/pagemaker/tool-icons/' + tool.icon)" />
                        <div class="name">{{ tool.label }}</div>
                    </div>
                </div>
            </div>

            <div v-else>
                <el-form label-width="90px" size="mini" label-position="right">
                    <el-form-item :label="color.name" v-for="(color, i) in colorItems" :key="i">
                        <el-color-picker @change="updateColor(color)" v-model="color.color" :predefine="predefineColors"></el-color-picker>
                    </el-form-item>
                </el-form>
            </div>
        </div>


    </div>
</template>


<script>
import {
    createPage,
    updatePage,
    updatePageName,
    deletePage,
    getPageList,
    setHome,
    clonePage,
    getPageDetail,
} from "@/api/page";
import { getColorConfigList, updateColorConfig, updateColor } from "@/api/color";
import { createLog } from "@/api/logs";

import notice from "./toolbarItems/notice";
import searchbar from "./toolbarItems/searchbar";
import banners from "./toolbarItems/banners";
import image from './toolbarItems/image';
import video from './toolbarItems/video';
// import navs from "./toolbarItems/navs";
import tours from './toolbarItems/tours';
import posts from "./toolbarItems/posts";
import houses from "./toolbarItems/houses";
import webview from "./toolbarItems/webview";
import text from "./toolbarItems/text";
import blank from "./toolbarItems/blank";
// import news from "./toolbarItems/news";
import brokers from './toolbarItems/brokers'
import follow from './toolbarItems/follow'
import zhaofang from './toolbarItems/zhaofang'
import videos from './toolbarItems/videos'
import myselflogin from "./toolbarItems/myselflogin";
import btns from "./toolbarItems/btns"
import hotnews from './toolbarItems/hotnews';
import newslist from './toolbarItems/newslist'
import scoregood from "./toolbarItems/scoregood";
import signdata from "./toolbarItems/signdata";
import auctionhouses from "./toolbarItems/auctionhouses";
// import block from './toolbarItems/block'

export default {
    props: {},
    computed: {

        pageKey: function () {
            return this.$store.state.pagemaker.pageKey;
        },

        pages: function () {
            return this.$store.state.pagemaker.pages
        },

        loading: {
            get() {
                return this.$store.state.pagemaker.loading

            },
            set(val) {
                this.$store.commit("pagemaker/setLoading", val);
            },
        },

        pageId: {
            get() {
                return this.$store.state.pagemaker.pageId

            },
            set(val) {
                this.$store.dispatch("pagemaker/loadPage", val);

            },
        },

        modules: {
            get() {
                return this.$store.state.pagemaker.pageModules;
            },
            set(modules) {
                this.$store.commit("pagemaker/setModules", modules);
            },
        },
    },
    components: {},
    watch: {
    },

    mounted: function () {
        this.$store.dispatch('pagemaker/loadPageList')
        this.$store.dispatch('pagemaker/loadTabbarList')
        this.loadColorData()
        // this.loadTabbars()
    },
    methods: {
        dbClickHandle: function (index) {
            console.log('db click', index)
            var page = this.pages[index]
            this.currentNameEditIndex = index
        },

        updateColor(color){
            updateColor({
                key: color.key,
                color: color.color
            }).then((resp) => {
                if (resp.code != 0) {
                    return
                }
                this.$store.dispatch('myconfig/loadMyconfig')
            })
        },

        importHandle: function (res) {
            console.log('res', res)
            if (res.status != 0) {
                this.$message.error(res.error)
                return
            }
            this.loadPages();
            this.$message.success("导入页面成功")
        },

        selectPageHandle: function (pageId) {
            this.currentNameEditIndex = null
            if (pageId != this.pageId) {
                this.pageId = pageId;
            }
        },
        saveNameHandle: function () {
            // 失去焦点后保存修改page名称
            if (this.currentNameEditIndex == null) {
                return false;
            }
            var page = this.pages[this.currentNameEditIndex];
            if (!page) {
                return false;
            }
            var _this = this;
            this.currentNameEditIndex = null;
            updatePageName(page)
                .then()
                .then((res) => {
                    // ok
                    if (res.status == 1) {
                        // 改名失败,重新加载
                        getPageDetail(page.id).then((resp) => {
                            page.name = resp.data.name;
                            _this.$set(_this.pages, this.currentNameEditIndex, page);
                        });
                    }
                });
        },

        clickModulesHandle: function (tool) {
            var modules = this.modules;
            if (modules.length >= this.maxModulesCount) {
                var msg =
                    "当前页面最多允许添加" +
                    this.maxModulesCount +
                    "个模块，无法继续添加";
                //this.$message.error(msg, "禁止操作");
                //return false;
            }
            // 重新开辟内从空间，防止array引用
            var module = JSON.parse(JSON.stringify(tool.initPayload));

            // 初始化一些常用字段，防止因为缺失字段，导致无法同步绑定的问题
            module.id = this.genModuleId();
            module.name = tool.key;
            module.label = tool.label;
            module.width = !module.width ? { size: 'full', editable: true } : module.width
            module.height = !module.height ? { min: 1, max: 1200, value: 'auto', editable: false } : module.height
            module.padding = !module.padding ? { top: false, bottom: false, editable: true } : module.padding
            module.margin = !module.margin ? { top: false,bottom: false, editable: true } : module.margin
            module.radius = !module.radius ? { value: 0, editable: true } : module.radius
            module.shadow = !module.shadow ? { value: 'off', editable: true } : module.shadow
            module.background = !module.background ? { cat: 'default', color: '#FFFFFF', image: "", default: "#FFFFFF" } : module.background

            // modules.push(module);
            if (tool.key == 'myselflogin') {
                // 检查modules是否已有登录模块，已有登录模块则不添加
                let hasLoginModule = modules.some(module => module.name == 'myselflogin');
                if (hasLoginModule) {
                    this.$message.error('页面中已存在登录模块，无法重复添加')
                    return false
                }

                // 登录组件必须位于最前面
                modules.unshift(module)
            } else if (module.insert_position == 'top') {
                modules.unshift(module)
            } else {
                modules.push(module)
            }
            // 某些模块自动添加一个分隔
            if (module.withBlank) {
                var _res = this.tools.filter((item, i) => {
                    if (item.key === "blank") {
                        return true;
                    }
                });
                //有报错，先注释 TODO
                // var blankModule = JSON.parse(JSON.stringify(_res[0].initPayload));
                // blankModule.id = this.genModuleId();
                // blankModule.label = _res[0].label;
                // blankModule.name = _res[0].key;
                // modules.push(blankModule);
            }
            this.$store.commit('pagemaker/setModules', modules);
            // this.modules = modules;
            var operation = '管理员在' + this.pageKey + '界面添加了' + tool.label + '模块';
            createLog({
                type: '界面设计器管理',
                operation: operation
            }).then(() => { })
            this.$message.success("模块已添加");
        },

        toolItemClickHandle: function (tool) {
            // create module

            if (tool.key == 'webview') {
                this.$confirm("添加webview组件后，其他组件将被清空，是否添加?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    this.modules = []
                    this.clickModulesHandle(tool)
                });
            } else {
                this.clickModulesHandle(tool)
            }
        },

        genModuleId: function () {
            // 生成module 的id
            var max = 0;
            this.modules.forEach((m, i) => {
                if (m.id && m.id > max) {
                    max = m.id;
                }
            });
            return max + 1;
        },

        addPageHandle: function () {
            this.loading = true;
            var page = {
                modules: [],
                config: {
                    padding: "no",
                    bg: {
                        blur: 0,
                        cat: "default",
                        color: "#f9f9f9",
                        defaultColor: "#f9f9f9",
                        image: "",
                    },
                    title: {
                        bgColor: "#1989fa",
                        color: "#ffffff",
                        value: "页面标题",
                    },
                    color: {},
                },
            };
            createPage(page).then((res) => {
                this.loading = false;
                if (res.status != 0) {
                    return false;
                }
                this.$message.success("页面已创建");
                this.loadPages();
            });
        },

        setHomeHandle: function (page) {
            this.loading = true;
            setHome(page.id).then((res) => {
                this.loading = false;
                this.loadPages();
                if (res.status == 0) {
                    this.$message.success('已设置为首页')
                }
            });
        },

        copyPageHandle: function (page) {
            this.loading = true;
            clonePage(page.id).then((res) => {
                this.loading = false;
                this.loadPages();
            });
        },

        deletePageHandle: function (page) {
            if (page.is_system) {
                return false;
            }
            this.$confirm("确定要删除这个页面吗？", "删除页面").then((res) => {
                deletePage(page.id).then((res) => {
                    if (res.status != 0) {
                        return false;
                    }
                    // 删除成功
                    this.$message.success("已删除");
                    this.loadPages();
                    if (page.id == this.pageId) {
                        // TODO 删除页面后，通知main组件
                    }
                });
            });
        },
        loadPages: function () {
            // todo
            this.$store.dispatch('pagemaker/loadPageList')
        },
        loadColorData: function () {
            getColorConfigList().then((resp) => {
                this.colorItems = resp.data.map((item) => {
                    return item;
                });
                // this.loading = false;
            });
        },
    },
    data() {
        return {
            maxModulesCount: 20,
            currentNameEditIndex: null,
            toolPanelName: "modules",
            tools: [
                {
                    name: '基础模块', items: [btns, notice, searchbar, image, video, banners, text, blank],
                },

                {
                    name: '内容模块', items: [posts, houses,  tours, videos, brokers, hotnews, newslist, scoregood, signdata, webview],
                },

                {
                    name: '互动模块', items: [follow, zhaofang, myselflogin],
                },
            ],
            // tabbars: [],
            tabbarid: null,
            colorItems: [],
            predefineColors: [
                    '#ff4500',
                    '#ff8c00',
                    '#ffd700',
                    '#90ee90',
                ]
        };
    },
};
</script>

<style scoped>
::-webkit-scrollbar {
    width: 0px;
}

.tools {
    color: #333;
    background: #ffffff;
    font-size: 12px;
    height: 100%;
}

.tools .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.tool-item {
    width: 75px;
    height: 75px;
    border: 1px solid #f5f5f5;
    margin: 0 5px 10px 5px;
    border-radius: 2px;
    font-size: 12px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    cursor: pointer;
    float: left;
    user-select: none;
}


.modules-group {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
}


.modules-list {
    width: 100%;
}

.modules-list .tool-item:nth-child(3n) {
    margin-right: 0px;
}

.tool-item img {
    width: 40px;
    margin-bottom: 6px;
}

.tool-item:hover {
    cursor: pointer;
    border: 1px solid #1989fa;
}

.tools-title {
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    margin-top: 20px;
    border: 1px solid #e5e9f2;
    height: 38px;
    border-radius: 38px;
    font-size: 14px;
}


/* .pages-list {} */

.pages-list ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.pages-list ul li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    user-select: none;
    height: 41px;
    line-height: 42px;
    padding-left: 10px;
    padding-right: 12px;
    margin-bottom: 12px;
    border: 1px solid #e8eae9;
    border-radius: 4px;
    background-color: #fafafa;
    user-select: none;
    cursor: pointer;
}

.pages-list ul li.active .name {
    color: #1989fa;
}

.pages-list ul li .name {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    overflow-x: hidden;
    overflow-y: hidden;
    width: calc(100% - 50px);
}

.pages-list ul li .name-edit input {
    height: 30px;
}

.pages-list ul li .page-actions {
    width: 93px;
    text-align: right;
}

.pages-list ul li .page-actions i {
    font-size: 16px;
    margin-left: 6px;
    cursor: pointer;
}

.pages-list .page-actions i:hover {
    color: #1989fa;
}

.pages-list .page-actions i.el-icon-delete:hover {
    color: red;
}

.pages-list ul li .page-actions i.disabled {
    color: rgba(0, 0, 0, 0.2);
}

.pages-list li.add-page {
    text-align: center;
    justify-content: center;
    align-items: center;
}

.pages-list li.add-page:hover {
    color: #1989fa;
}
.toast{
    height: 100%;display: flex;flex-direction: column;align-items: center;justify-content: center;
}
</style>
